<?php

namespace app\index\model;

use Think\Db;
use think\Model;

// 部门模型
class Departments extends Model
{
    protected $table = "departments";
    protected $pk = "department_id";
    protected $field = [
        "department_id",        //部门id
        "department_name",      //部门名称
    ];

    public function selectDepartmentNameWithEmpCount()
    {
        $department_list = $this->alias("d")
            ->fieldRaw("d.department_name , count(e.employee_id) as emloyee_count")
            ->leftjoin("employees e", "d.department_id = e.department_id")
            ->group("d.department_name")->select();
        return $department_list;
    }

    public function selectDepartmentAvgSalary()
    {
        $department_list = $this->alias("d")
            ->fieldRaw("d.department_name,avg(e.salary) as avg_salary")
            ->leftjoin("employees e", "d.department_id = e.department_id")
            ->group("d.department_name")->select();
            return $department_list;
    }

    public function addDepartmentDataAndRetId($data){
        $add_result = $this->allowField(true)->save($data);
        if ($add_result != false) {
            return $this->department_id;
        } else {
            return false;
        }
    }

    public function updDepartmentName($data,$where){
        $upd_result = $this->allowField(true)->force()->save($data,$where);
        dump($upd_result);
        return $upd_result;
    }
}
